import type { INotificationOptions, INotificationResolved } from "./src/notification"
import notificationConstraction from "./src/notification.vue"
import { render, createVNode, isRef, type Ref } from "vue"
import _ from "lodash-es"

const BASE_GAD = 16 // 基础间距
let seed = 1

const notificationList = new Map<HTMLElement | null, { id: string, el: HTMLElement, n: number }>()

function createNotification(options: INotificationOptions) {
  const container = document.createElement("div")

  const resolved = resolvedOptions(options)

  const vm = createVNode(notificationConstraction, {
    ..._.omit(resolved, 'position')
  })

  render(vm, container)

  document.body.appendChild(container.firstChild as Node)

  notificationList.set(vm.el as HTMLElement, {
    id: resolved.id,
    el: vm.el as HTMLElement,
    n: seed
  })

}

function resolvedOptions(options: INotificationOptions): INotificationResolved {

  const className: string = 'right'
  // if (options.position && (options.position === 'top-right' || options.position === 'bottom-right')) {
  //   className = 'right'
  // } else if (options.position && (options.position === 'top-left' || options.position === 'bottom-left')) {
  //   className = 'left'
  // } else {
  //   className = 'right'
  // }

  let top: number = BASE_GAD
  notificationList.forEach(notify => {
    const height = notify.el.getBoundingClientRect().height
    top += height
    top += BASE_GAD
  })

  return {
    title: options.title || '',
    message: options.message || '',
    id: `vt-notification-${seed++}`,
    position: options?.position || 'top-right',
    style: options.style || `top: ${top}px`,
    class: className,
    duration: options.duration ?? 4000,
    showClose: options.showClose ?? true,
    close: (el: HTMLElement | null | Ref<HTMLElement | null>) => {
      const element: HTMLElement | null = isRef(el) ? el.value : el
      const distance = element!.getBoundingClientRect().height;
      element?.remove()
      notificationList.delete(element)
      asyncMoveAll(seed, distance)

    },
  }
}

/**
 * 
 * @param n 序号
 * @param distance 移动距离 
 */
function asyncMoveAll(n: number, distance: number) {
  notificationList.forEach((notify) => {
    if (notify.n <= n) {
      notify.el.style.top = notify.el.getBoundingClientRect().top - distance + 'px'
    }
  })
}

const VtNotification = createNotification

export { VtNotification }

